import { Toggle, ToggleStatus } from "../hooks/useToggle";
import Offset from "./Offset";
import Portal from "./Portal";
import Position from "./Position";
import TooltipBody from "./TooltipBody";
import { FC, ReactElement, ReactNode, useRef } from "react";

type RenderTooltipContent = () => ReactNode;

interface TooltipProps {
  content: RenderTooltipContent;
  offset: Offset;
  position: Position;
  target: ReactElement;
}

const Tooltip: FC<TooltipProps> = ({ content, offset, position, target }) => {
  const targetRef = useRef<HTMLDivElement>(null);

  const renderTarget = (toggle: Toggle): ReactElement => {
    const show = (): void => {
      toggle(ToggleStatus.Open);
    };
    const hide = (): void => {
      toggle(ToggleStatus.Close);
    };
    return (
      <div ref={targetRef} onMouseEnter={show} onMouseLeave={hide}>
        {target}
      </div>
    );
  };

  const renderContent = (): ReactElement => (
    <TooltipBody offset={offset} position={position} targetRef={targetRef}>
      {content()}
    </TooltipBody>
  );

  return <Portal target={renderTarget} content={renderContent} />;
};

export default Tooltip;
